package com.huanhuan.query;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;


//遍历查询
public class Amount_Query {
    public static void main(String[] args) throws Exception{
        //1.创建客户端对象
        //创建服务主机名 和 Web 通信端口
        final String hostname = "localhost";
        final int port = 9200;
        final String scheme = "http";
        HttpHost httpHost = new HttpHost( hostname, port, scheme );


        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(httpHost)
        );


        //1.查询索引中全部的数据
        SearchRequest request = new SearchRequest();
        request.indices("user");

        request.source(new SearchSourceBuilder().query( QueryBuilders.matchAllQuery() ) );

        SearchResponse response = client.search( request, RequestOptions.DEFAULT );

        SearchHits hits = response.getHits();

        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());

        //数据遍历出来
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }

        //关闭ES 资源
        client.close();
    }
}
